package com.zhiyou100.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.Test;


public class DBUtil {
	private final String URL="jdbc:mysql://localhost:3306/zy_crm";
	private final String USER="root";
	private final String PWD="admin";
	private static final String DRIVER="com.mysql.jdbc.Driver";
	private PreparedStatement ps = null;
	private Connection conn = null;
	private ResultSet rs = null;

	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Test
	public void getConn() {
		try {
			conn = DriverManager.getConnection(URL, USER, PWD);
			System.out.println(conn+"******************");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}


	public int update(String sql,Object...obj) {
		getConn();
		int a = 0;
		try {
			ps = conn.prepareStatement(sql);
			for(int i = 0;i < obj.length;i++) {
				ps.setObject((i+1), obj[i]);
			}
			a = ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return a;
	}

	public ResultSet select(String sql,Object...obj) {
		getConn();
		try {
			ps = conn.prepareStatement(sql);
			for(int i = 0;i < obj.length;i++) {
				ps.setObject((i+1), obj[i]);
			}
			rs = ps.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}

	public void close() {
		try {
			if(rs!=null) {
				rs.close();
			}
			if(ps!=null) {
				ps.close();
			}
			if(conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
	}
}
